# Analysis of micro-cleavage experiment
# Nils B. Weidmann (nils.weidmann@uni-konstanz.de)
# December 2014

library(doBy)
library(ggplot2)
library(grid)
library(mgcv)

setwd("/Users/nilsw/Projects/MicroCleavageABM/R")

# function to clean up NetLogo column names
clean.colnames <- function (x) { gsub("^X.|[.]$", "", colnames(x)) } 

# read data
data <- read.csv("main-experiment.csv", skip=6)

colnames(data) <- clean.colnames(data)
data$alliancetype[data$alliances == "\"none\""] <- "No alliance"
data$alliancetype[data$alliances == "\"accurate-onesided\""] <- "C: Internal motive"
data$alliancetype[data$alliances == "\"inaccurate-onesided\""] <- "B: Observed behavior"
data$alliancetype[data$alliances == "\"biased-onesided\""] <- "A: Group membership"
data$alliance[data$alliances == "\"none\""] <- "No"
data$alliance[data$alliances != "\"none\""] <- "Yes"
data$urban <- "Rural"
data$urban[data$sw_p_rewire > 0.5] <- "Urban"

data$conflictrate <- data$num.violent / (data$num.agents * data$n.runs)
data$conflictrate.macro <- data$num.violent.macro / (data$num.agents * data$n.runs)



# experiment 1
data1 <- subset(data, alliancetype=="No alliance")

# Figure 2(a)
pdf("exp1_violence.pdf", width=6, height=5)
ggplot(data1, aes(sw_p_rewire, conflictrate)) + geom_smooth(colour="black", size=1.1) + xlab("Level of urbanization") + ylab("Conflict rate") + theme_bw()
dev.off()

# Figure 2(b)
pdf("exp1_clustering.pdf", width=6, height=5)
ggplot(data1, aes(sw_p_rewire, mean.prop.similar)) + geom_smooth(colour="black", size=1.1) + xlab("Level of urbanization") + ylab("Average ideological similarity")  + theme_bw()
dev.off()


# Experiment 2: Effect of alliances on total violence

# Figure 3
pdf("exp2_violence.pdf", width=8, height=5)
ggplot(data, aes(sw_p_rewire, conflictrate, group=alliances, linetype=factor(alliancetype))) + geom_smooth(colour="black", size=1.1) + xlab("Level of urbanization") + ylab("Conflict rate") + scale_linetype_manual("Alliance type", values=c("dotdash", "dotted", "dashed", "solid")) + theme_bw() + theme(legend.key.width = unit(2, "cm"))
dev.off()


# Experiment 3: Effect of alliances on macro violence

# Figure 4
pdf("exp3_macro_violence.pdf", width=8, height=5)
ggplot(data, aes(sw_p_rewire, conflictrate.macro, group=alliances, linetype=factor(alliancetype))) + geom_smooth(colour="black", size=1.1) + xlab("Level of urbanization") + ylab("Macro conflict rate") + scale_linetype_manual("Alliance type", values=c("dotdash", "dotted", "dashed", "solid")) + theme_bw() + theme(legend.key.width = unit(2, "cm"))
dev.off()



